<template>
  <div>
    <folder-tree
      ref="folderTree"
      :name="name"
      :menu-folder-list="menuFolderList"
      :menu-file-list="menuFileList"
      :click-functions="clickFunctions"
      @dbl-click-node="changeNode"
      @create-file="createFile"
      @rename="rename"
      @delete="askDelete"
    />
    <file-upload-dialog ref="fileUploadDialog" />
  </div>
</template>

<script>
import FolderTree from '@/components/FolderTree';
import FileUploadDialog from '@/views/functions/components/FileUploadDialog';

export default {
  name: 'FunctionFolderTree',
  components: {
    FolderTree,
    FileUploadDialog
  },
  data() {
    return {
      name: 'functions',
      menuFolderList: [
        { style: 'item', type: 'rename', title: '重命名' },
        { style: 'item', type: 'remove', title: '删除' },
        { style: 'item', type: 'upload', title: '上传' },
        {
          style: 'submenu',
          title: '新建',
          children: [
            {
              style: 'item',
              type: 'buildFolder',
              title: '文件夹',
              icon: 'icon-build-fold'
            },
            {
              style: 'item',
              type: 'buildFile',
              title: '脚本',
              icon: 'icon-build-script'
            }
          ]
        }
      ],
      menuFileList: [
        { style: 'item', type: 'open', title: '打开' },
        { style: 'divider' },
        { style: 'item', type: 'rename', title: '重命名' },
        { style: 'item', type: 'remove', title: '删除' }
      ]
    };
  },
  methods: {
    changeNode(node) {
      const data = node.data;
      console.log(data);
      if (data.isFile) {
        this.$store.dispatch('functions/getFile', data)
          .then(() => {
          })
          .catch((err) => {
            this.$message.error(err);
          });
        // 添加打开文件提示，文件夹不提示
      }
    },
    setData(data) {
      this.$store.commit('functions/setTreeData', data);
    },
    clickFunctions(type, options) {
      const { node, data } = options;
      switch (type) {
        case 'open':
          this.changeNode(node);
          break;
        case 'buildFolder':
        case 'buildFile':
          // 先展开树节点，再显示编辑框
          this.$refs.folderTree.expandNode(data);
          this.$store.commit('functions/append', {
            nodeType: 'child',
            type,
            data
          });
          break;
        case 'remove':
          this.askDelete(options, data);
          break;
        case 'rename':
          this.rename(data);
          break;
        case 'upload':
          this.$store.commit('functions/setUploadNode', data);
          this.$refs.fileUploadDialog.show();
          break;
        default:
          this.$message.info('二期开发');
      }
    },
    askDelete(options, data) {
      const str = data.isFile ? '文件' : '文件夹';
      if (data.id === data.fatherId) {
        this.$confirm(`系统生成的index.py为函数唯一入口，不可删除`, '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }
      this.$confirm(`此操作将永久删除该${str}(${data.label}), 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('functions/remove', options);
        this.$store.dispatch('functions/remove', data);
      });
    },
    rename(data) {
      if (data.id === data.fatherId || data.id === 'config' || data.id === 'sample' || data.id === 'requirement') {
        this.$message({
          message: `系统生成的${data.label}文件不可被重命名`,
          type: 'warning'
        });
      } else {
        this.$store.commit('functions/editName', data);
      }
    },
    async createFile(node, filename) {
      const { data } = node;
      const labels = ['requirements.txt', 'config.yaml', 'sample.py', 'index.py'];
      // 加trim防止重名，原本的会出现可以命名的情况
      if (data.isFile && data.path === '' && labels.includes(filename.trim())) {
        this.$message.warning(filename + '只允许通过按钮添加！请勿自行创建！');
        this.$store.commit('functions/remove', { node, data });
        return;
      }
      // 在函数的使用里面一般不会出现使用空格命名的包或者是库
      if (filename.trim().indexOf(' ') !== -1) {
        filename = data.isFile ? 'untitled.py' : 'new_folder';
        this.$message({
          message: "文件夹/文件命名不可以带有空格，请修改名称'",
          type: 'warning'
        });
      }
      data.label = filename.trim();
      if (data.isFile === false) {
        await this.$store.dispatch(`functions/updateChildPath`, data);
      } else if (data.isFile === true) {
        await this.$store.dispatch(`functions/handleEditorFileName`, data);
      }
      const flag = data.isFile && data.isFirstBuild;
      data.isFirstBuild = false;
      this.$store.dispatch(`functions/append`, data);
      if (flag) {
        this.$store.dispatch(`functions/buildFiles`, data);
      }
    }
  }
};
</script>
